package com.hn.shoutchinese.othertrans.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.hn.net.Kit;
import com.hn.shoutchinese.othertrans.service.IOtherTransService;

public class OtherTransServiceImpl implements IOtherTransService {

	@Override
	public List<String> getOtherTransWords(String word) {

		// http://dict.baidu.com/s?wd=%D7%D4%BC%BAself&tn=dict&dt=example
		String head = "http://dict.baidu.com/s?wd=";
		String url = null;
		try {
			String wordURL = java.net.URLEncoder.encode(word, "gb2312");
			url = head + wordURL + "&tn=dict&dt=explain";
		} catch (Exception e) {
			e.printStackTrace();
		}
//		System.out.println(url);
		String content = Kit.httpRequest(url, null, "GET", "gb2312");

		// 调试本地
		// String content = Tools
		// .readFile("D:\\eclipse_workspace\\indigo\\shoutchinese-robot\\res\\othertrans.htm");
		// System.out.println(content);

		int iNotFound = content.indexOf("未找到和您的");
		// 如果有对应翻译
		if (iNotFound == -1) {
			int iStartStep1 = content.lastIndexOf("词典解释");
			String key1 = "<span class=\"enfont\">1.</span>";
			String key2 = "<span class=\"enfont\">";

			int iStartStep2 = content.indexOf(key1, iStartStep1)
					+ key1.length();
			int iStartStep3 = content.indexOf(key2, iStartStep2)
					+ key2.length();

			int iEnd1 = content.indexOf("</span>", iStartStep3);
			String words1 = content.substring(iStartStep3, iEnd1);
			if (words1 != null) {
				String[] strWords = words1.split("; ");
				List<String> arrWords = new ArrayList<String>();
				for (int i = 0; i < strWords.length; i++) {
					if (strWords[i].length() < 20) {
						arrWords.add(strWords[i]);
					}
				}
				return arrWords;
			}
		}

		return null;
	}

	public static void main(String[] args) {
		OtherTransServiceImpl ots = new OtherTransServiceImpl();
		ots.getOtherTransWords("那里");
	}

}
